
#include <condefs.h>
#pragma hdrstop

 #define _free( x ) if ( x ){ free( x ); x = NULL; }

  #include <conio.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>

  LONG tdSize;
  LONG count;

  FILE *bg,
       *df,
       *tf;

  char outfile[512];
  char index,
       *p;

  BYTE BG_Tile[3][0x20];
  BYTE buffer[0x08];

  BYTE data;
  BYTE *tiles = NULL;

  BYTE BGBase = 0;

//---------------------------------------------------------------------------
#pragma argsused
int main( int argc, char **argv )
{
  clrscr( );
  //
  if ( argc > 1 )
  {
    strcpy( outfile, argv[1] );
    p = strchr( outfile, '.' );
    if ( p )
      strcpy( p, ".jon" );
    else
      strcat( outfile, ".jon" );
    //
    tf = fopen( argv[1], "rb" );
    df = fopen( outfile, "wb" );
    bg = fopen( argv[2], "rb" );
    //
    if ( !tf || !df || !bg )
    {
      fcloseall( );
      printf( "Error: Could not open one or more user files." );
      return -1;
    }
    // Load up the BG tile data
    fread( &BG_Tile, 1, 0x60, bg );
    fclose( bg );

    // Load up the Font tiles to convert
    fseek( tf, 0, SEEK_END );
    tdSize = ftell( tf );
    fseek( tf, 0, SEEK_SET );
    //
    tiles = ( BYTE *)malloc( tdSize );
    if ( !tiles )
    { //
      fcloseall( );
      _free( tiles );
      printf( "Fatal Error: could not allocate needed memory for TILES." );
      return -1;
    }
    // Load up the tile data
    fread( tiles, 1, tdSize, tf );
    fclose( tf );

    // Try to convert the tile data
    count = 0;
    while( count < tdSize )
    { //
      BGBase = 0;
      if ( (count >= 0x0080 && count < 0x0100) || ( count >= 0x0200 && count < 0x0280) )
        BGBase = 1;
      else
      if ( count < 0x80 || count >= 0x0280 )
        BGBase = 0;
      else
        BGBase = 2;
      //
      memcpy( buffer, &tiles[ count ], 8 );
      count += 8;
      // Layer 1 and 2
      for ( index = 0; index < 8; index++ )
      {
        fputc( BG_Tile[BGBase][ 0x00 + index + index ] | buffer[ index ], df );
        fputc( (BG_Tile[BGBase][ 0x00 + index + index + 1 ] | buffer[ index ]) ^ buffer[ index ] , df );
      }

      // Layer 3 & 4
      for ( index = 0; index < 8; index++ )
      {
        fputc( (BG_Tile[BGBase][ 0x10 + index + index ] | buffer[ index ]) ^ buffer[ index ] , df );
        fputc( (BG_Tile[BGBase][ 0x10 + index + index + 1 ] | buffer[ index ]) ^ buffer[ index ] , df );
      }
    }
  }
  else
  {
    printf( "Usage: Tiles.ext BackGroundTile.ext" );
    return -1;
  }

  //
  fcloseall( );
  _free( tiles );

  return 0;
}
